package cn.ijero.floatwindow

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.widget.MediaController
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isVisible
import cn.ijero.floatwindow.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    private var currentPosition = 0

    private val mediaController by lazy {
        MediaController(this)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)

        setContentView(binding.root)
        initViewListener()
    }

    private fun initViewListener() {
        binding.apply {
            floatingButton.isVisible = false
            playImageView.setOnClickListener {
                // 开始播放
                videoView.setVideoPath("android.resource://${packageName}/${R.raw.video}")
                videoView.setMediaController(mediaController)
                videoView.start()
                playImageView.isVisible = false
                floatingButton.isVisible = true
            }

            floatingButton.setOnClickListener {
                if (!Settings.canDrawOverlays(this@MainActivity)) {
                    val intent = Intent()
                        .setAction(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
                        .setData(Uri.parse("package:$packageName"))
                    startActivityForResult(intent, 0)
                    return@setOnClickListener
                }
                currentPosition = binding.videoView.currentPosition
                moveTaskToBack(true)

                if (FloatService.isRunning) {
                    FloatService.stop(this@MainActivity)
                }
                FloatService.start(this@MainActivity, currentPosition,binding.videoView.isPlaying)
            }
        }
    }

    override fun onPause() {
        super.onPause()
        currentPosition = binding.videoView.currentPosition
    }

    override fun onResume() {
        super.onResume()
        FloatService.stop(this@MainActivity)
        if (FloatService.playPosition != -1) {
            binding.videoView.seekTo(FloatService.playPosition)
        } else {
            binding.videoView.seekTo(currentPosition)
        }
        binding.videoView.start()
    }

}